package com.yanxu.proxy.proxy_dynamic;


import com.yanxu.proxy.base.IOrderService;
import com.yanxu.proxy.base.Order;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/4/15-2025
 * @Description: 这里用一句话描述这个类的作用
 */
public class OrderServiceDynamicProxy2 {


    public Object getProxy(IOrderService target) {
        Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //前置增强
                beforeMethod(args);

                Object result = method.invoke(target, args);

                //后置增强
                afterMethod();
                return result;
            }
        });

        return proxy;
    }

    private Integer beforeMethod(Object[] args){
        System.out.println(" ~~~~~~ before method");
        int num=0;
        if(args[0] instanceof Order){
            Order order = (Order) args[0];
            Integer userId = order.getUserId();
            num = userId % 2;
            System.out.println(" ~~~~~~ 动态代理分配到db【"+num+"】 处理数据!");
        }
        return num;
    }

    private void afterMethod(){
        System.out.println(" ~~~~~~ after method");
    }
}